package com.itbac.config.sentinel;

import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
import com.alibaba.csp.sentinel.datasource.*;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * SPI 机制  service provider interface
 * 在jar包的META-INF/services/目录里同时创建一个以服务接口命名的文件。该文件里的内容就是实现该服务接口的具体实现类。
 *
 * sentinel持久化
 * 1.写当前类,读写规则的具体逻辑
 * 2.resources下创建目录和配置文件
 * \META-INF\services\com.alibaba.csp.sentinel.init.InitFunc
 * 3.配置文件写当前类的全路径
 */
public class FilePersistence implements InitFunc {

    @Value("spring.application.name")
    private String appcationName;

    //定义规则转换器，把 String 数据,解析成 sentinel 规则
    private Converter<String, List<AuthorityRule>> authorityRuleListParser = source ->
            JSON.parseObject(source, new TypeReference<List<AuthorityRule>>() {
            });
    private Converter<String, List<DegradeRule>> degradeRuleListParser = source ->
            JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {
            });
    private Converter<String, List<FlowRule>> flowRuleListParser = source ->
            JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            });
    private Converter<String, List<ParamFlowRule>> paramFlowRuleListParser = source ->
            JSON.parseObject(source, new TypeReference<List<ParamFlowRule>>() {
            });
    private Converter<String, List<SystemRule>> systemRuleListParser = source ->
            JSON.parseObject(source, new TypeReference<List<SystemRule>>() {
            });
    /**
     * 初始化方法
     */
    @Override
    public void init() throws Exception {
        //规则路径
        String ruleDir = System.getProperty("user.home") + "/sentinel-rules/" + appcationName;
        //规则文件
        String flowRuleFile = ruleDir + "/flow-rule.json";
        String degradeRuleFile = ruleDir + "/degrade-rule.json";
        String systemRuleFile = ruleDir + "/system-rule.json";
        String authorityRuleFile = ruleDir + "/authority-rule.json";
        String paramFlowRuleFile = ruleDir + "/param-flow-rule.json";
        //创建文件夹
        this.mkdirIfNotExits(ruleDir);
        //创建文件
        this.createFileIfNotExits(flowRuleFile);
        this.createFileIfNotExits(degradeRuleFile);
        this.createFileIfNotExits(systemRuleFile);
        this.createFileIfNotExits(authorityRuleFile);
        this.createFileIfNotExits(paramFlowRuleFile);

        //读规则，注册到规则管理器，写规则
        //流控规则
        ReadableDataSource<String,List<FlowRule>> flowRuleRDS = new FileRefreshableDataSource<>(flowRuleFile, flowRuleListParser);
        FlowRuleManager.register2Property(flowRuleRDS.getProperty());
        WritableDataSource<List<FlowRule>> flowRuleWDS = new FileWritableDataSource<>(flowRuleFile, this::encodeJson);
        WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS);

        //降级规则
        ReadableDataSource<String,List<DegradeRule>> degradeRuleRDS = new FileRefreshableDataSource<>(degradeRuleFile, degradeRuleListParser);
        DegradeRuleManager.register2Property(degradeRuleRDS.getProperty());
        WritableDataSource<List<DegradeRule>> degradeRuleWDS = new FileWritableDataSource<>(degradeRuleFile, this::encodeJson);
        WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS);

        //系统规则
        ReadableDataSource<String,List<SystemRule>> systemRuleRDS = new FileRefreshableDataSource<>(systemRuleFile, systemRuleListParser);
        SystemRuleManager.register2Property(systemRuleRDS.getProperty());
        WritableDataSource<List<SystemRule>> systemRuleWDS = new FileWritableDataSource<>(systemRuleFile, this::encodeJson);
        WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS);

        //授权规则，黑白名单
        ReadableDataSource<String,List<AuthorityRule>> authorityRuleRDS = new FileRefreshableDataSource<>(authorityRuleFile, authorityRuleListParser);
        AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty());
        WritableDataSource<List<AuthorityRule>> authorityRuleWDS = new FileWritableDataSource<>(authorityRuleFile, this::encodeJson);
        WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS);

        //热点参数流控规则
        ReadableDataSource<String,List<ParamFlowRule>>  paramFlowRuleRDS = new FileRefreshableDataSource<>(paramFlowRuleFile, paramFlowRuleListParser);
        ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty());
        WritableDataSource<List<ParamFlowRule>>  paramFlowRuleWDS = new FileWritableDataSource<>(paramFlowRuleFile, this::encodeJson);
        ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS);

    }
    //对象生成json字符串
    private <T> String encodeJson(T t) {
        return JSON.toJSONString(t);
    }

    //创建文件夹
    private void mkdirIfNotExits(String pathName) {
        File file = new File(pathName);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
    //创建文件
    private void createFileIfNotExits(String fileName) throws IOException {
        File file = new File(fileName);
        if (!file.exists()) {
            file.createNewFile();
        }

    }


}
